

from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.http import JsonResponse

from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView


import logging

logger = logging.getLogger(__name__)


class LoginView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request):
        logger.debug('login')
        try:
            username = request.data.get('username')
            password = request.data.get('password')
            # 验证账户和密码
            user: User = authenticate(request=request, username=username, password=password)
            if user is not None and user.is_active:
                logger.debug('authenticate success')
                # 存储session
                login(request, user)
                logger.debug('login success')

                # 生成token
                token = ''
                logger.debug('token success')

                return Response({
                    'code': 'login success',
                    'info': user.username,
                    'token': token
                })
                pass
            else:
                return Response({
                    'code': 'login failure',
                    'info': '登录失败',
                })
        except Exception as e:
            return Response({
                'code': 'Exception',
                'info': str(e),
            })

    pass


class LogoutView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request: Request):
        logger.debug('logout')
        logout(request)
        return Response({
            'code': 'logout success',
            'info': 'rest/user/login',
        })

    pass
